#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include <arpa/inet.h>
#include <unistd.h>

#include "wget.h"
#include "log.h"

char *create_http_request(http_url *url)
{
    const char *request_tpl = "GET %s HTTP/1.1\r\n\
Host: %s\r\n\
Connection: Close\r\n\r\n";

    int size = strlen(request_tpl) + strlen(url->uri) + strlen(url->host) -4 + 1;
    
    char *http_request = (char *)malloc(size);

    sprintf(http_request, request_tpl, url->uri, url->host);

    debug_log("http_request\t%s\n", http_request);

    return http_request;
}


int wget(http_url *url, const char *filename)
{
    // create
    int sockfd = 0;

    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
        exit(1);
    }

    // connect
    struct sockaddr_in servaddr;
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(url->port);

    if(inet_pton(AF_INET, url->ip, &servaddr.sin_addr) < 0){
        exit(1);
    }

    if(connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0){
        exit(1);
    }

    // write
    char *http_request = create_http_request(url);
    
    if(write(sockfd,http_request,strlen(http_request)) < 0){
        exit(1);
    }

    // read
    char response_buf[128] = {0};
    int len = 0;

    if((len = read(sockfd, response_buf, 128)) > 0){
        printf("%s",response_buf);
    }

    // close 
    close(sockfd);

    return 0;
}
